package config

import (
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v3"
	"log"
)

// 通过接口可以实现解析api与rpc两种结构体
type Config interface {
	GetConfig() error
}

func (c *ApiConf) GetConfig() error {
	clientConfig := constant.ClientConfig{
		NamespaceId:         ApiC.Nacos.ClientConfig.NamespaceId,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// At least one ServerConfig>protoc --version
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      ApiC.Nacos.ServerConfig.IpAddr,
			ContextPath: "/nacos",
			Port:        ApiC.Nacos.ServerConfig.Port,
			Scheme:      "http",
		},
	}
	// Create naming service for service discovery
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		log.Fatal("创建nacos实例失败")
		return err
	}
	config, err := client.GetConfig(vo.ConfigParam{
		DataId: ApiC.Nacos.ConfigParam.DataId,
		Group:  ApiC.Nacos.ConfigParam.Group,
	})
	if err != nil {
		log.Fatal("获取远程配置失败")
		return err
	}

	err = yaml.Unmarshal([]byte(config), &ApiC)
	if err != nil {
		log.Fatal("解析远程配置失败")
		return err
	}
	log.Println("api远程配置文件解析成功")
	log.Println(ApiC)
	return nil
}

func (c *RpcConf) GetConfig() error {
	clientConfig := constant.ClientConfig{
		NamespaceId:         RpcC.Nacos.ClientConfig.NamespaceId,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// At least one ServerConfig>protoc --version
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      RpcC.Nacos.ServerConfig.IpAddr,
			ContextPath: "/nacos",
			Port:        RpcC.Nacos.ServerConfig.Port,
			Scheme:      "http",
		},
	}
	// Create naming service for service discovery
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		log.Fatal("创建nacos实例失败")
		return err
	}
	config, err := client.GetConfig(vo.ConfigParam{
		DataId: RpcC.Nacos.ConfigParam.DataId,
		Group:  RpcC.Nacos.ConfigParam.Group,
	})
	if err != nil {
		log.Fatal("获取远程配置失败")
		return err
	}

	err = yaml.Unmarshal([]byte(config), &RpcC)
	if err != nil {
		log.Fatal("解析远程配置失败")
		return err
	}
	log.Println("rpc远程配置文件解析成功")
	log.Println(RpcC)
	return nil
}
